package us.wili.dev.common.model.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * Created by JasonY on 17/2/19.
 */
public class IdcardValidator implements ConstraintValidator<Idcard, Object> {

    private final static String IDCARD_REG = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
    private Pattern idcardPattern = Pattern.compile(IDCARD_REG);

    @Override
    public void initialize(Idcard idcard) {

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }

        if (!(value instanceof String)) {
            return false;
        }

        return idcardPattern.matcher(value.toString()).matches();
    }
}
